<?php
/**
 *
 * @package avp
 * @version $Id: $
 * @copyright (c) 2006 Jan-Willem van Ganswijk, Stefan van Essen
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
define("IN_SCRIPT", "TRUE"); //Voor de evil haxx0rz.

$root = "./../";
include($root . "includes/config.inc.php");
// Installer Config
$checkfiles = "includes/config.inc.php;images/;templates/compiled/";
$db_file = 'db.sql';
$php_version_req = '4.2.0';
$gd_version_req = '2.0';

$step = (int)$_GET["step"];

?>
<html>
<head>
<title>Avatar Panel Installation Script</title>
<style type="text/css">
body {
  background:#000 url(../templates/zen/images/stripesblack.png) repeat;
  color:#FFF;
  font-family:Arial,Helvetica,sans-serif;
  font-size:15px;
  margin:0px;
}
table {
	color:#000;
	font-size: 14px;
	width: 750px;
	border-collapse: collapse;
}
td {
	border-bottom: 1px solid #ADC243;

	border-collapse: collapse;
	color: white;
	padding: 3px 6px;
}
td.head {
	background-color: #ADC243;
	color: black;
	text-align: center;
}
h2 {
	font-size: 20px;
}
input {
	background-color: #000;
	border: 1px solid white;
	color: white;
}
.center {
	text-align: center;
}
a,
a:hover,
a:active,
a:visited {color: #FFF;}
h2 a {
	text-decoration: none;
}
h2 a:hover {
	font-style: italic;
}

</style>
</head>
<body>

<?php

if ($step == 0 || empty($step)) {

    ?>
<center>
<h1>Welcome</h1>
<p>Welcome to the installation of Avatar Panel</p>
<h2><a href="install.php?step=1">Continue</a></h2>
</center>
<?php
} elseif ($step == 1) {
    $error = false;    // Huge requirement check, checks for the correct php version and GD2 support

    $gdavailable_formats = 0;
    $comments = array();

    $reqcheck['Environment']['phpver']['str'] = "PHP Version";
    $reqcheck["Environment"]["phpver"]['msg'] = phpversion();
    if (version_compare(phpversion(), $php_version_req) >= 0) {
        $reqcheck['Environment']['phpver']['state'] = 1;
    } else {
        $reqcheck['Environment']['phpver']['state'] = 0;
        $error = true;
        $comments[] = "Error: Avatar Panel doesn't support your current php version";
    }

    $reqcheck["Environment"]["register_globals"]['str'] = "register_globals";
    if (ini_get('register_globals')) {
        $reqcheck["Environment"]["register_globals"]['msg'] = "active";
        $reqcheck["Environment"]["register_globals"]['state'] = 2;
        $comments[] = "Warning: register_globals is turned on, which might cause some security issues.";
    } else {
        $reqcheck["Environment"]["register_globals"]['msg'] = "inactive";
        $reqcheck["Environment"]["register_globals"]['state'] = 1;
    }
    $reqcheck["Environment"]["modrewrite"]['str'] = "Apache mod_rewrite";
    if ($_GET['modrewrite'] == 'on') {
        $reqcheck["Environment"]["modrewrite"]['state'] = 1;
        $reqcheck["Environment"]["modrewrite"]['msg'] = "loaded";
    } else {
        $reqcheck["Environment"]["modrewrite"]['state'] = 2;
        $comments[] = "Warning: Apache's mod_rewrite is not loaded. Your avatars will only be available using an .php file extension. Some websites do not allow this.";
        $reqcheck["Environment"]["modrewrite"]['msg'] = "unavailable";
    }

    if (extension_loaded('gd')) {
        $gdinfo = gd_info();
        $gdversion = ereg_replace('[[:alpha:][:space:]()]+', '', $gdinfo['GD Version']);

        $reqcheck["GD Library"]["gdver"]['str'] = 'GD Version:';
        $reqcheck["GD Library"]["gdver"]['msg'] = $gdversion;

        if (version_compare($gdversion, $gd_version_req) >= 0) {
            $reqcheck["GD Library"]["gdver"]['state'] = 1;
        } else {
            $reqcheck["GD Library"]["gdver"]['state'] = 0 ;
            $error = true;
            $comments[] = "Error: Avatar panel doesn't support your current version of the GD library.";
        }
        $reqcheck["GD Library"]["gdgifread"]['str'] = 'GIF Read Support:';
        if ($gdinfo["GIF Read Support"]) {
            $reqcheck["GD Library"]["gdgifread"]['state'] = 1;
            $reqcheck["GD Library"]["gdgifread"]['msg'] = "enabled";
            $gdavailable_formats++;
        } else {
            $reqcheck["GD Library"]["gdgifread"]['state'] = 2;
            $reqcheck["GD Library"]["gdgifread"]['msg'] = "disabled";
        }
        $reqcheck["GD Library"]["gdgifcreate"]['str'] = 'GIF Create Support:';
        if ($gdinfo["GIF Create Support"]) {
            $reqcheck["GD Library"]["gdgifcreate"]['state'] = 1;
            $reqcheck["GD Library"]["gdgifcreate"]['msg'] = "enabled";
            $gdavailable_formats++;
        } else {
            $reqcheck["GD Library"]["gdgifcreate"]['state'] = 2;
            $reqcheck["GD Library"]["gdgifcreate"]['msg'] = "disabled";
        }

        $reqcheck["GD Library"]["gdjpeg"]['str'] = 'JPEG Support:';
        if ($gdinfo["JPG Support"]) {
            $reqcheck["GD Library"]["gdjpeg"]['state'] = 1;
            $reqcheck["GD Library"]["gdjpeg"]['msg'] = "enabled";
            $gdavailable_formats++;
        } else {
            $reqcheck["GD Library"]["gdjpeg"]['state'] = 2;
            $reqcheck["GD Library"]["gdjpeg"]['msg'] = "disabled";
        }
        $reqcheck["GD Library"]["gdpng"]['str'] = 'PNG Support:';
        if ($gdinfo["PNG Support"]) {
            $reqcheck["GD Library"]["gdpng"]['state'] = 1;
            $reqcheck["GD Library"]["gdpng"]['msg'] = "enabled";
            $gdavailable_formats++;
        } else {
            $reqcheck["GD Library"]["gdpng"]['state'] = 2;
            $reqcheck["GD Library"]["gdpng"]['msg'] = "disabled";
        }

        if ($gdavailable_formats < 1) {
            $comments[] = "Error: GD doesn't support enough file-formats to work properly.";
            $error = true;
        } elseif ($gdavailable_formats < 4) {
            $comments[] = "Warning: Not all possible file formats are supported by your gd2 installation. AVP will be able to work, but not fully functional.";
        }
    } else {
        $reqcheck["GD Library"]["gdver"]['str'] = 'GD Support:';
        $reqcheck["GD Library"]["gdver"]['msg'] = 'No GD support available';
        $comments[] = "Error: GD is not enabled.";
        $error = true;
        $reqcheck["GD Library"]["gdver"]['state'] = 0;
    }

    ?>
<center>
<h1>Step 1: Requirements</h1>
<p>AVP needs write-access to its configuration file and to upload directory. Also PHP <?php echo $php_version_req ?> and the GD library are required.</p>
<table>
<?php
    foreach($reqcheck as $catname => $checkcat) {
        echo "<tr><td align=\"center\" colspan=\"3\" class=\"head\">" . $catname . "</td></tr>";
        foreach($checkcat as $checkitem) {
            switch ($checkitem["state"]) {
                case 0:
                    $checkimg = $root . 'templates/zen/images/error.png';
                    break;
                case 1:
                    $checkimg = $root . 'templates/zen/images/ok.png';
                    break;
                case 2:
                    $checkimg = $root . 'templates/zen/images/warn.png';
                    break;
            }
            echo "<tr><td>{$checkitem['str']}</td><td align=\"center\">{$checkitem['msg']}</td><td width=\"25\" class=\"center\"><img src=\"{$checkimg}\" /></tr>";
        }
    }

    ?>
<tr>
	<td class="head" colspan="3">Files</td>
</tr>
<?php
	$filerror = false;
    $checkfiles = explode(";", $checkfiles);
    foreach($checkfiles as $file) {
        if (is_writable($root . $file)) {
            echo "<tr><td>{$file}</td><td align=\"center\">Writeable</td><td width=\"25\" class=\"center\"><img src=\"{$root}templates/zen/images/ok.png\" /></tr>";
        } else {
            echo "<tr><td>{$file}</td><td align=\"center\">Unwriteable</td><td width=\"25\" class=\"center\"><img src=\"{$root}templates/zen/images/error.png\" /></tr>";
            $filerror = true;
        }
    }
    if($filerror == true) {
		$error = true;
		$comments[] = 'Please make sure all the required files are writeable.';
	}

    ?>
<tr>
	<td class="head" colspan="3">Messages</td>
</tr>
<?php
    if (count($comments) < 1 && $error == false) {
        $comments[] = 'All requirements are met!';
    }
    foreach($comments as $comment) {
        echo "<tr><td class=\"center\" colspan=\"3\">{$comment}</td></tr>";
    }

    ?>
</table>
<?php if ($error == false) {
        echo '<h2><a href="install.php?step=2">Continue</a></h2>';
    } else {
        echo "<h2><a href=\"install.php?step=1\">Refresh</a></h2>";
    }

    ?>
</center>
<?php
} elseif ($step == 2) {

    ?>
<center>
<h1>Step 2: Database Configuration</h1>
<p>This step will configure the config file containing the database acces data.</p>
<form action="install.php?step=3" method="post">
	<table cellpacing="0" celpadding="3" border="0">
		<tr>
			<td colspan="3" class="head">Database Configuration</td>
		</tr>
		<tr>
			<td>Hostname:</td><td><input type="text" name="dbhost" /></td><td>The database host, usually "localhost".</td>
		</tr>
		<tr>
			<td>Username:</td><td><input type="text" name="dbuser" /></td><td>The username used to acces the database.</td>
		</tr>
		<tr>
			<td>Password:</td><td><input type="text" name="dbpass" /></td><td>The password to be used with the username.</td>
		</tr>
		<tr>
			<td>Database Name:</td><td><input type="text" name="dbname" /></td><td>The name of the database.</td>
		</tr>
		<tr>
			<td>Table Prefix:</td><td><input type="text" name="dbprefix" value="avp_" /></td><td>The prefix which wil precede every table name. This makes running multiple instances of AVP possible.</td>
		</tr>
		<tr>
			<td colspan="3" align="center"><input type="submit" value="Submit" /></td>
		</tr>
	</table>
</form>

</center>
<?php
} elseif ($step == 3) {
    $config_file = "<?php

if(!defined('IN_SCRIPT')) {
    die();
}

\$sql_server = '" . $_POST['dbhost'] . "';
\$sql_user =  '" . $_POST['dbuser'] . "';
\$sql_pass =  '" . $_POST['dbpass'] . "';
\$sql_database =  '" . $_POST['dbname'] . "';
\$sql_prefix =  '" . $_POST['dbprefix'] . "';


?>";

    if (!@mysql_connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpass']) || !@mysql_select_db($_POST['dbname']) || !@mysql_query('SHOW TABLES')) {

        ?>
    <center>
<h1>Step 3: Error</h1>
<p>The database information you've enterd is incorrect, please retry.</p>
<a href="install.php?step=2">Retry</a>
</center>
<?php
        exit;
    } else {
        if (!$fp = fopen($root . "includes/config.inc.php", "w"))
            die("Config file is not writable");
        fputs($fp, $config_file);
        fclose($fp);
    }

    ?>
<center>
<h1>Step 3</h1>
<p>The database configuration has been stored succesfully. The configuration file is available for later editing in "includes/config.inc.php"</p>
<h2><a href="install.php?step=4">Continue</a></h2>
</center>
<?php
} elseif ($step == 4) {
    $tblcount = 0;

    ?>
<center>
<h1>Step 4: Inserting Data into Database</h1>
<p></p>

	<?php
    include($root . "includes/database.class.php");
    $db = new dbWrapper($sql_user, $sql_pass, $sql_server, $sql_database, $sql_prefix);

    $sqlfile = file($db_file);
    $sqlfile = implode("", $sqlfile);
    $queries = explode("~~~", $sqlfile);
    foreach($queries as $query) {
        eval("\$query = trim($query);");
        $db->query($query);
        $tblcount++;
    }

    ?>
<p><?php echo $tblcount ?> Tables have succesfully been created/modified.</p>
<h2><a href="install.php?step=5">Continue</a></h2>
</center>
<?php
} elseif ($step == 5) {

    ?>
<center>
<h1>Step 5: Login Details</h1>
<p>This step will set the username/password combination needed to login.</p>
<form action="install.php?step=6" method="post">
	<table cellpacing="0" celpadding="3" border="0">
		<tr>
			<td colspan="2" class="head">Login Configuration</td>
		</tr>
		<tr>
			<td>Username:</td><td><input type="text" name="username" /></td>
		</tr>
		<tr>
			<td>Password:</td><td><input type="password" name="password" /></td>
		</tr>
		<tr>
			<td>Retype Password:</td><td><input type="password" name="password_retype" /></td>
		</tr>

		<tr>
			<td colspan="2" align="center"><input type="submit" value="Submit" /></td>
		</tr>
	</table>
</form>

</center>
<?php
} elseif ($step == 6) {
    if ($_POST["password"] != $_POST["password_retype"]) {
        die("Passwords do not match. <a href=\"install.php?step=5\">return</a>");
    }
    include($root . "includes/database.class.php");
    $requesturl = explode('install/install.php', $_SERVER['REQUEST_URI']);
    $webpath = 'http://' . $_SERVER['HTTP_HOST'] . $requesturl[0];
    $mod_rewrite = ($_GET['modrewrite'] == 'on') ? 1 : 0;
    $db = new dbWrapper($sql_user, $sql_pass, $sql_server, $sql_database, $sql_prefix);
    $db->query("UPDATE `{$db->get_table( "settings" )}`
                 SET `username`='{$_POST["username"]}',
	                   `userpass`='" . md5($_POST["password"]) . "',
	                   `webpath`='$webpath',
	                   `mod_rewrite`=$mod_rewrite
	               WHERE 1");

    ?>
<center>
<h1>Step 5 - Finished!</h1>
<p>The installation is now finished. Please delete the /install directory before continuing.</p>
<h2><a href="../admin/index.php">Continue to AVP!</a></h2>
</center>
<?php
}

?>
</body>
</html>